<?php
namespace app\agent\controller;

use think\Db;
use think\Request;

class Index extends  Base
{


    public function index()
    {
        $mesCount = Db::name('message')
        ->where(['level'=>'2','rceID'=>session('agents.id'),'Statue'=>0])
        ->count();
        return view('index/index',['mesCount'=>$mesCount]);
    }

    public function welcome()
    {
        $agents = Db::name('agents')->where('id',session('agents.id'))->find();
        $vip = Db::name('vip')->where('id',$agents['vid'])->find()['name'];
        $count = Db::name('users')->where(['aid'=>session('agents.id')])->count();
        return view('index/welcome',['agents'=>$agents,'vip'=>$vip,'count'=>$count]);
    }

    // 查看客户
    public function showuser(Request $request)
    {
        $get=$request->get();
        $get['p']=isset($get['p'])?$get['p']:config('paginate.list_rows');
        $id=session('agents.id');
        if(empty($_GET['name'])){
            $data=Db::name('users')
                ->field(true)
                ->where('aid',$id)
                ->order('id desc')
                ->paginate($get['p'],false,['query'=>$get]);
            $balance=Db::name('users')
                ->where('aid',$id)
                ->sum('balance');
        }else{
            $data=Db::name('users')
                ->field(true)
                ->where('aid',$id)
                ->where('name|phonenumber|assetaccount','like',"%{$_GET['name']}%")
                ->order('id desc')
                ->paginate($get['p'],false,['query'=>$get]);
            $balance=Db::name('users')
                ->where('aid',$id)
                ->where('name|phonenumber|assetaccount','like',"%{$_GET['name']}%")
                ->sum('balance');
        }

        $arr = [];
        foreach($data as $k => $v){
            $ywy = Db::name('salesman')->where(['aid'=>session('agents.id'),'id'=>$v['yid']])->find()['yname'];
            $arr[$v['yid']] = $ywy;
        }
        $list=$data->items();
        $page=$data->render();
//        $agent = Db::name('agents')->where('id',session('agents.id'))->find()['show'];
//        if($agent==0) {
//            foreach ($list as $k => $v) {
//                if (strlen($v['name']) == 11) {
//                    $list[$k]['name'] = substr_replace($v['name'], '*****', 3, 5);
//                } else {
////                    $list[$k]['name'] = substr_replace($v['name'], '*', 3, 3);
//                }
//                $list[$k]['phonenumber'] = substr_replace($v['phonenumber'], '*****', 3, 5);
//            }
//        }
        return view('user/index',['list'=>$list,'page'=>$page,'get'=>$get,'arr'=>$arr,'balance'=>$balance]);
    }

    public function show(Request $request)
    {
        $id=$request->get('id');
        $user=Db::name('users')->field('name,assetaccount,fwq')->find($id);
        $qjgj = Db::name('futures_api')->where(['id'=>$user['fwq']])->find();
        if($qjgj['title']=='jt'){
            $req['Action']='ReqQryAccountInfo';
            $req['ChdAccountID']=$user['assetaccount'];
            $req['UserID']=$qjgj['sa'];
            ksort($req);
            $url='';
            foreach ($req as $k=>$v){
                $url=$url.$k.'='.$v.'&';
            }
            $req=rtrim($url,'&');
            //var_dump($req);
            $sign=md5($req.'&UserKey='.$qjgj['sapass']);
            $req=$req.'&Sign='.$sign;
            //var_dump($req);
            $url=$qjgj['api'].'?'.$req;
            // var_dump($url);
            $res=https_request($url);
            //var_dump($res);die;
            //var_dump(json_decode($res,true));die;
            $data=json_decode($res,true);
            if(strlen($user['name'])==11){
                $user['name']=substr_replace($user['name'], '*****', 3, 5);
            }else{
                $user['name']=substr_replace($user['name'], '*', 3, 3);
            }
            $da = [];
            if($data['ErrorID']==0) {
                $da['dqqy'] = $data['LowAvailable']/100;//劣后
                $da['Credit'] = $data['HighBalance']/100;//优先
                $da['Margin']=$data['CurrMargin'];//保证金
                $da['Balance'] = $data['Balance']/100;//当前权益
                $da['Available'] = $data['Available']/100;//可用资金
//                $data['']=$data['BadAmount'];
                return ['status'=>1,'res'=>$da,'name'=>$user['name']];
            }else{
                return ['status'=>2,'msg'=>$data['ErrorMsg'],'name'=>$user['name']];
            }

        }else{
            $url="{$qjgj['api']}queryaccount?requestid=6&sa={$qjgj['sa']}&sapass={$qjgj['sapass']}&account={$user['assetaccount']}";
            $data=https_request($url);
            $objectxml = simplexml_load_string($data);//将文件转换成 对象
            $xmljson= json_encode($objectxml );//将对象转换个JSON
            $xmlarray=json_decode($xmljson,true);//将json转换成数组
            if(strlen($user['name'])==11){
                $res['name']=substr_replace($user['name'], '*****', 3, 5);
            }else{
                $res['name']=substr_replace($user['name'], '*', 3, 3);
            }
            if($xmlarray['Result']['Error']['Code']!=0){
                return ['status'=>2,'msg'=>$xmlarray['Result']['Error']['Message'],'name'=>$user['name']];
            }else{
                return ['status'=>1,'res'=>$xmlarray['Result']['Summary'],'name'=>$user['name']];
            }
        }
        return $res;
    }

    // 查看交易记录
    public function showlist(Request $request)
    {
        $get=myarr($request->get());
        $get['p']=isset($get['p'])?$get['p']:config('paginate.list_rows');
        $get['kp']=isset($get['kp'])?$get['kp']:'';
        $get['mm']=isset($get['mm'])?$get['mm']:'';
        $get['hy']=isset($get['hy'])?$get['hy']:'';
        $get['zzh']=isset($get['zzh'])?$get['zzh']:'';
        $get['phonenumber']=isset($get['phonenumber'])?$get['phonenumber']:'';
        $get['name']=isset($get['name'])?trim($get['name']):'';
        $get['start']=isset($get['start'])?$get['start']:date('Y-m-d',strtotime('-1 day'));
        $get['end']=isset($get['end'])?$get['end']:date('Y-m-d');
        $jystart=str_replace('-','',$get['start']);
        $jyend=str_replace('-','',$get['end']);
        $where['agents']=['=',session('agents.id')];
        if($get['kp']!=''){
            $where['Kaiping']=['=',$get['kp']];
        }
        if($get['mm']!=''){
            $where['Business']=['=',$get['mm']];
        }
        if($get['hy']!=''){
            $where['Contract']=['=',$get['hy']];
        }
        if($get['zzh']!=''){
            $where['Subaccount']=['=',$get['zzh']];
        }
        if($get['phonenumber']!=''){
            $where['phonenumber']=['=',$get['phonenumber']];
        }
        if($get['name']!=''){
            $where['name']=['=',$get['name']];
        }
        if($get['start']!=''&&$get['end']!=''){
            $where['TradingDday']=['between',[$jystart,$jyend]];
        }
//        dump($where);die;
        $list=Db::name('transaction')
            ->alias('a')
            ->join('lc_users b','a.uid=b.id')
            ->field('a.*,b.name,b.phonenumber')
            ->where($where)
            ->order('id desc')
//            ->select();
            ->paginate($get['p'],false,['query'=>$get]);
//        dump($list);die;
        $page=$list->render();
        $list=$list->items();
        $count['Count']=Db::name('transaction')
            ->alias('a')
            ->join('lc_users b','a.uid=b.id')
            ->field('a.*,b.name,b.phonenumber')
//            ->field(true)
            ->where($where)
            ->sum('Count');
        $count['Poundage']=Db::name('transaction')
            ->alias('a')
            ->join('lc_users b','a.uid=b.id')
            ->field('a.*,b.name,b.phonenumber')
//            ->field(true)
            ->where($where)
            ->sum('Poundage');
        $Float=Db::name('transaction')
            ->alias('a')
            ->join('lc_users b','a.uid=b.id')
            ->field('a.*,b.name,b.phonenumber')
//            ->field(true)
            ->where($where)
            ->column('`Float`');
        $count['Float'] = 0;
        foreach ($Float as $v){
            $count['Float'] += $v;
        }
        $Profit=Db::name('transaction')
            ->alias('a')
            ->join('lc_users b','a.uid=b.id')
            ->field('a.*,b.name,b.phonenumber')
//            ->field(true)
            ->where($where)
            ->column('`Profit`');
        $count['Profit'] = 0;
        foreach ($Profit as $v){
            $count['Profit'] += $v;
        }
        $count['Brokerage']=Db::name('transaction')
            ->alias('a')
            ->join('lc_users b','a.uid=b.id')
            ->field('a.*,b.name,b.phonenumber')
//            ->field(true)
            ->where($where)
            ->sum('Brokerage');

        return view('transaction/showlist',['list'=>$list,'page'=>$page,'get'=>$get,'count'=>$count]);

    }

    public function xq(Request $request)
    {
        $id=$request->get('id');
        $list=Db::name('transaction')->find($id);
        return $list;
    }

    // 出入金统计
    public function crsummary(Request $request)
    {
        $get=myarr($request->get());
        $aid=session('agents.id');
        $get['p']=isset($get['p'])?$get['p']:config('paginate.list_rows');
        $get['start']=isset($get['start'])?$get['start']:date('Y-m-d',strtotime('-1 day'));
        $get['end']=isset($get['end'])?$get['end']:date('Y-m-d');
        //$get['p']=isset($get['p'])?$get['p']:config('paginate.list_rows');
        $jystart=str_replace('-','',$get['start']);
        $jyend=date('Y-m-d',strtotime($get['end'].'+1 day'));

        $get['name']=isset($get['name'])?trim($get['name']):'';
//        $jystart=str_replace('-','',$get['start']);
//        $jyend=str_replace('-','',$get['end']);
//        $jystart=date('Y-m-d H:i:s',strtotime($jystart));
//        $jyend=date('Y-m-d H:i:s',strtotime($jyend));

        if($get['name']!=''){
            $where['name']=['=',$get['name']];
        }
        if($get['start']!=''&&$get['end']!=''){
            $where['time']=['between',[$jystart,$jyend]];
        }
        $where['aid']=['=',$aid];
        $list=Db::name('cashlog')->alias('a')
            ->join('lc_users b','a.uid=b.id')
            ->field('a.*,b.name')
            ->where($where)
            ->where('type','in','5,6')
            ->order('id desc')
            ->paginate($get['p'],false,['query'=>$get]);
        $page=$list->render();
        $list=$list->items();
        $userall=Db::name('users')->field('id')->where('name','like','%'.$get['name'].'%')->where('aid',$aid)->column('id');
        $tj['rj']=Db::name('cashlog')->alias('a')
            ->join('lc_users b','a.uid=b.id')
            ->field('a.*,b.name')
            ->where($where)
            ->where('type',5)
            ->sum('price');
        $tj['cj']=Db::name('cashlog')->alias('a')
            ->join('lc_users b','a.uid=b.id')
            ->field('a.*,b.name')
            ->where($where)
            ->where('type',6)
            ->sum('price');
        return view('transaction/showsummary',['list'=>$list,'page'=>$page,'get'=>$get,'tj'=>$tj]);
    }


    public function extension()
    {
        $id=session('agents.id');
        $host=$_SERVER['HTTP_HOST'];
        $url='http://'.$host.'/index/register/index?refereecode='.$id;
        $qrcode = $this->scerweima($url);
        return view('user/extension',['url'=>$url,'qrcode'=>$qrcode]);
    }

    public function scerweima($url=''){
        require_once EXTEND_PATH.'phpqrcode/phpqrcode.php';

        $value = $url;                  //二维码内容

        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 5;           //生成图片大小

        //生成二维码图片
        $filename = '/static/vip_agent/qrcode/'.microtime().'.png';
        $path=ROOT_PATH.'/public/'.$filename;
        \QRcode::png($value,$path , $errorCorrectionLevel, $matrixPointSize, 2);

        return $filename;

    }
}
